const express = require('express')
const router = express.Router();

const WordVector = require("./../model/wordvector");
const { Op } = require("sequelize");
const { CalculateWordDistance } = require("../utils/wordDistance")


router.post('/', async (req, resp)=>{
    // if(!req.session.mail){
    //     resp.json({
    //         rescode:200,
    //         msg:'未登录',
    //         type:'error'
    //     });
    //     return;
    // }
    try {
        let words = req.body.wordList;
        console.log(words);
        let wordList = await WordVector.findAll({
            attributes: [
                'word', 'w1', 'w2', 'w3', 'w4', 'w5', 'w6', 'w7', 'w8', 'w9',
                'w10', 'w11', 'w12', 'w13', 'w14', 'w15', 'w16', 'w17', 'w18', 'w19',
                'w20', 'w21', 'w22', 'w23', 'w24', 'w25', 'w26', 'w27', 'w28', 'w29',
                'w30', 'w31', 'w32', 'w33', 'w34', 'w35', 'w36', 'w37', 'w38', 'w39',
                'w40', 'w41', 'w42', 'w43', 'w44', 'w45', 'w46', 'w47', 'w48', 'w49',
                'w50'
            ],
            where: {
                word: {
                    [Op.in]: words
                },
            }
        })
        // console.log(wordList.length);
        // console.log(wordList);
        let score;
        if(wordList.length <= 1){
           score = 0;
        } else {
            score = 0;
            console.log('------------begin here----------');
            for(let i=0;i<wordList.length;i++){
                for(let j=i+1;j<wordList.length;j++){
                    let cur = CalculateWordDistance(wordList[i],wordList[j]);
                    console.log(words[i],words[j],cur);
                    score += cur;
                }
            }
            console.log('--------end here-----------');
            // console.log((wordList.length * (wordList.length-1) / 2));
            score = score / (wordList.length * (wordList.length-1) / 2);
            score = score*100;
            score = parseInt(score);
        }
        resp.json({
            rescode: 200,
            score: score
        })
    } catch (error) {
        console.log(error)
        resp.json({
            rescode:400,
            msg:error.toString()
        })
    }
});

module.exports = router;
